#include "ThreadCache.h"
#include "CentralCache.h"
#include <algorithm>

void* ThreadCache::FetchfromcentralCache(size_t index, size_t size)
{
	size_t batch = min(_freelist[index].maxsize(), Sizeclass::getNumFromcentral(size));
	if (batch == _freelist[index].maxsize())
	{
		_freelist[index].maxsize() += 1;
	}
	void* start = nullptr;
	void* end = nullptr;
    

	size_t actulnum = CentralCache::getinstance()->FetchtoThread(start, end, batch, size);
	assert(actulnum > 1);
	if (actulnum == 1)
	{
		assert(start == end);
		return start;
	}
	else
	{
		_freelist[index].pushrange(nextobj(start), end,actulnum-1);
		return start;
	}
}

void ThreadCache::listtoolong(freelist* list, size_t size)
{
	void* start = nullptr;
	void* end = nullptr;
	list->poprange(start, end, list->maxsize());
	CentralCache::getinstance()->RealseListTospan(start,size);
}

void* ThreadCache::setAlloc(size_t size)
{
	size_t arrsize = Sizeclass::roundup(size);
	size_t index = Sizeclass::getindex(size);
	assert(size <= MAX_Bytes);
		if (!_freelist[index].empty())
	{
			_freelist[index].pop();
	}
		else
	{
			return FetchfromcentralCache(index, arrsize);
	}
}

void ThreadCache::deAlloc(void* ptr, size_t size)
{  
	assert(ptr);
	assert(size <= MAX_Bytes);
	size_t index = Sizeclass::getindex(size);
	_freelist[index].push(ptr);
}